package cn.cxy.imagecompress_luban_demo

import android.Manifest
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.text.TextUtils
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.qw.soul.permission.SoulPermission
import com.qw.soul.permission.bean.Permission
import com.qw.soul.permission.callbcak.CheckRequestPermissionListener
import top.zibin.luban.CompressionPredicate
import top.zibin.luban.Luban
import top.zibin.luban.OnCompressListener
import java.io.File


class MainActivity : AppCompatActivity() {
    private val baseImageDir = Environment.getExternalStorageDirectory().absolutePath + "/1/"
    private val sourceImageUri = Uri.fromFile(File("$baseImageDir/test.png"))

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        applyPermissionAndCompress()
    }

    private fun compressImageWithLuban() {
        Luban.with(this)
                .load(sourceImageUri)
                .ignoreBy(100)
                .setTargetDir(baseImageDir)
                .filter(CompressionPredicate { path -> !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif")) })
                .setCompressListener(object : OnCompressListener {
                    override fun onStart() {
                        // TODO 压缩开始前调用，可以在方法内启动 loading UI
                    }

                    override fun onSuccess(file: File?) {
                        Log.v("MainActivity", file?.absolutePath)
                    }

                    override fun onError(e: Throwable) {
                        // TODO 当压缩过程出现问题时调用
                    }
                }).launch()
    }

    private fun applyPermissionAndCompress() {
        SoulPermission.getInstance()
                .checkAndRequestPermission(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        object : CheckRequestPermissionListener {
                            override fun onPermissionOk(permission: Permission) {
                                compressImageWithLuban()
                            }

                            override fun onPermissionDenied(permission: Permission) {
                            }
                        })
    }
}